#!/bin/bash
function echofile(){
    cat > init_$init_name << EOF
#!/bin/bash
# $init_name    启动$init_name
# chkconfig: 2345 55 25

# source function library
#. /etc/rc.d/init.d/functions

pidfile="$pidfile"
confdir="$confdir"
scripts="$scripts"

start(){
    pid=\`cat \$pidfile 2> /dev/null\`
    [ -z "\$pid" ] || exitscripts 1
    [ -f \$confdir ] || exitscripts 2

    \$scripts && echo "启动完成" || exitscripts 3
    exit 0
}

stop(){
    pid=\`cat \$pidfile 2> /dev/null\`
    [ ! -z "\$pid" ] && \$scripts -s stop && echo "stop完成" || exitscripts 6
    pid=\`cat \$pidfile 2> /dev/null\`
    if [ ! -z "\$pid" ];then
        kill \$pid && exitscripts 4
    fi
}

restart(){
    stop
    sleep 1
    start
}

reload(){
    \$scripts -s reload && echo "reload完成" || exitscripts 5
}

exitscripts(){
    case \$1 in
        1) echo "pid文件不为空，退出脚本" && exit 1
        ;;
        2) echo "找不到配置文件，请检查\$confdir" && exit 2
        ;;
        3) echo "启动失败" && exit 3
        ;;
        4) echo "stop失败，kill \$pid" && exit 4
        ;;
        5) echo "reload 失败" && exit 5
        ;;
        6) echo "stop失败，pid文件为空" && exit 6
        ;;
        7) echo "无有效参数，请指定参数(参考参数:start|stop|restart|reload)" && exit 7
        ;;
        *) echo "[error code: \$1 ]"
        ;;
    esac
}

case \$1 in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        restart
    ;;
    reload)
        reload
    ;;
    *)
        exitscripts 7
    ;;
esac
EOF
}
